<template>
  <div class="webShell-main">
    <div class="layout-container">
      <!-- 左侧面板 -->
      <div :class="{ 'collapsed': isCollapsed_webShell }" class="left-panel">
        <div class="panel-header">
          <div class="panel-title">{{ isCollapsed_webShell ? '' : '服务器列表' }}</div>
          <el-button class="collapse-btn" type="text" @click="toggleCollapse">
            <el-icon v-if="isCollapsed_webShell">
              <ArrowRight/>
            </el-icon>
            <el-icon v-else>
              <ArrowLeft/>
            </el-icon>
          </el-button>
        </div>
        <div class="panel-content">
          <el-button v-if="!isCollapsed_webShell" type="primary" @click="handleAddTabs">新增连接</el-button>
          <el-divider v-if="!isCollapsed_webShell">
            <el-icon>
              <star-filled/>
            </el-icon>
          </el-divider>
          <el-table v-if="!isCollapsed_webShell" :data="connectServerListData" style="width: 100%">
            <el-table-column align="center" label="服务器地址" prop="serverIp" width="135"/>
            <el-table-column align="center" label="操作" width="250">
              <template #default="scope">
                <div>
                  <el-button type="success" @click="handleConnectBtn(scope.row)">连接</el-button>
                  <el-button type="primary" @click="handleEditServerInfoBtn(scope.row)">编辑</el-button>
                  <el-button type="danger" @click="handleDeleteBtn(scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <!-- 右侧主内容 -->
      <div class="right-content">
        <el-tabs
            v-if="editableTabs.length > 0"
            v-model="editableTabsValue"
            class="full-height-tabs"
            closable
            type="card"
            @tab-remove="removeTab"
        >
          <el-tab-pane
              v-for="item in editableTabs"
              :key="item.name"
              :label="item.data.serverIp"
              :name="item.name"
          >
            <ConnectToSFTP :form-data="item.data"/>
          </el-tab-pane>
        </el-tabs>
        <div v-else class="prompt-container">
          <div class="history-connections">
            <div class="title-bar">
              <h3 class="history-title">连接列表</h3>
              <el-button type="primary" @click="toggleCollapse">编辑</el-button>
            </div>

            <div v-for="server in connectServerListData" :key="server.id" class="history-item"
                 @click="handleConnectBtn(server)">
              <el-icon class="connection-icon">
                <Link/>
              </el-icon>
              <span class="server-ip">{{ server.serverIp }}</span>
            </div>
            <div v-if="connectServerListData.length === 0" class="no-history">
              暂无历史连接记录
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加折叠状态下的浮标 -->
    <AddServerConnectDialog ref="addServerConnectRef" :dialog-visible="dialogVisible"
                            @close="handleCloseAddServerInfoDialog"
                            @update:dialogVisible="dialogVisible = $event"/>

    <EditServerConnectDialog ref="EditServerConnectRef"
                             :dialog-visible="EditDialogVisible" :form-data="EditFormData"
                             @close="handleCloseEditServerInfoDialog"
                             @update:dialogVisible="EditDialogVisible = $event"/>

    <DraggableFloatCom
        v-if="isCollapsed_webShell"
        @click="toggleCollapse"
    >

    </DraggableFloatCom>

  </div>
</template>

<style scoped>
/* 全局高度样式重置 */
:deep(html), :deep(body) {
  height: 100%;
  margin: 0;
  padding: 0;
}

.webShell-main {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.layout-container {
  display: flex;
  flex: 1;
  height: 100%;
  overflow: hidden;
}

.left-panel {
  width: 425px;
  transition: width 0.3s ease;
  border-right: 1px solid #e5e7eb;
  height: 100%;
  overflow: hidden;
  background-color: #fff;
}

.left-panel.collapsed {
  width: 0;
  padding: 0;
  margin: 0;
  border-right: none;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #e5e7eb;
}

.panel-title {
  font-weight: bold;
}

.collapse-btn {
  padding: 5px;
}

.panel-content {
  padding: 10px;
  height: calc(100% - 50px);
  overflow-y: auto;
}

.right-content {
  flex: 1;
  transition: all 0.3s ease;
  height: 100%;
  overflow: hidden;
}

.prompt-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: linear-gradient(135deg, #7b4397, #dc2430);
}

.prompt {
  font-size: 24px;
  color: white;
  text-align: center;
  padding: 10px;
  border-radius: 8px;
  background-color: rgba(0, 0, 0, 0.5);
}

/* Element UI Tabs 样式调整 */
:deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.el-tabs__header) {
  margin: 0 !important;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-tabs__content) {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

:deep(.el-tab-pane) {
  height: 100%;
  overflow: hidden;
}

.full-height-tabs {
  height: 100%;
  display: flex;
  flex-direction: column-reverse;
}

.history-connections {
  width: 80%;
  max-width: 600px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.history-title {
  margin-top: 0;
  margin-bottom: 16px;
  color: #1f2937;
  font-size: 18px;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 12px;
}

.history-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.history-item:hover {
  background-color: #f3f4f6;
}

.connection-icon {
  color: #1890ff;
  margin-right: 12px;
}

.server-ip {
  color: #374151;
  font-size: 14px;
}

.no-history {
  text-align: center;
  padding: 24px;
  color: #6b7280;
  font-size: 14px;
}

.title-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}
</style>

<script lang="ts" setup>
import {onBeforeUnmount, onMounted, ref} from 'vue'
import AddServerConnectDialog from '@/views/webShell/Dialog/AddServerConnectDialog.vue';
import EditServerConnectDialog from '@/views/webShell/Dialog/EditServerConnectDialog.vue';
import {ElMessage} from 'element-plus'
import {deleteServerById, getServerList} from '@/api/webShell/ServerList'
import DraggableFloatCom from '@/components/common/DraggableFloatCom.vue';
import {StarFilled} from '@element-plus/icons-vue'
import ConnectToServer from "@/views/webShell/mainPanel/components/ConnectToServer.vue";
import {ArrowLeft, ArrowRight} from '@element-plus/icons-vue'
import ConnectToSFTP from "@/views/webShell/SFTP/components/ConnectToSFTP.vue";

const connectServerListData = ref([])

const dialogVisible = ref(false)
const EditDialogVisible = ref(false)
const addServerConnectRef = ref(null)
const EditServerConnectRef = ref(null)

const editableTabsValue = ref('0')
const editableTabs = ref([])

const EditFormData = ref()


// 打开新增连接信息对话框
function handleAddTabs() {
  dialogVisible.value = true
}

// 打开编辑对话框
function handleEditServerInfoBtn(row: any) {
  EditFormData.value = row
  EditDialogVisible.value = true
}

// 从服务器获取服务器连接信息
function updateServerList() {
  getServerList().then(function (response: any) {
    connectServerListData.value = response.data.data
  })
      .catch(function (error: any) {
        // 处理错误情况
        console.log(error);
        ElMessage.error('获取服务器列表失败')

      });
}

// 添加服务器连接信息提交后 回调函数
function handleCloseAddServerInfoDialog() {
  updateServerList();
}

// 编辑服务器连接信息提交后 回调函数
function handleCloseEditServerInfoDialog() {
  updateServerList();
}

let tabIndex = 0

// 关闭列表，连接服务器
function handleConnectBtn(row: any) {
  let newTabIndex = `${++tabIndex}`
  isCollapsed_webShell.value = true;

  editableTabs.value.push({
    name: newTabIndex,
    data: row
  })
  editableTabsValue.value = newTabIndex
}

// 删除某个连接信息
function handleDeleteBtn(row: any) {
  console.log(row.id)
  deleteServerById(row.id).then(() => {
    ElMessage.success('删除服务器列表成功')
    updateServerList();
  }).catch(function (error: any) {
    // 处理错误情况
    console.log(error);
    ElMessage.error('删除服务器列表失败')

  });
}


// 删除终端连接
function removeTab(targetIndex: string) {

  const tabs = editableTabs.value

  // 当前激活的tab 对应的index
  let activeIndex = editableTabsValue.value

  if (activeIndex === targetIndex) {
    tabs.forEach((tab, index) => {
      if (tab.name === targetIndex) {
        const nextTab = tabs[index + 1] || tabs[index - 1]
        if (nextTab) {
          activeIndex = nextTab.name
        }
      }
    })
  }

  editableTabsValue.value = activeIndex
  editableTabs.value = tabs.filter((tab) => tab.name !== targetIndex)
}


onBeforeUnmount(() => {
  editableTabs.value = []
  editableTabsValue.value = ''
  editableTabs.value.forEach((tab) => {
    tab.term?.dispose()
  })
})

onMounted(() => {
  updateServerList()
})


// 添加折叠状态变量， 默认折叠状态
const isCollapsed_webShell = ref(true)

// 添加折叠切换方法
function toggleCollapse() {
  isCollapsed_webShell.value = !isCollapsed_webShell.value
}

</script>
